package com.qf.web.servlet;

import com.qf.domain.CartItem;
import com.qf.domain.Goods;
import com.qf.domain.User;
import com.qf.service.CartService;
import com.qf.service.GoodsService;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/*
 *                             _ooOoo_
 *                            o8888888o
 *                            88" . "88
 *                            (| -_- |)
 *                            O\  =  /O
 *                         ____/`---'\____
 *                       .'  \\|     |//  `.
 *                      /  \\|||  :  |||//  \
 *                     /  _||||| -:- |||||-  \
 *                     |   | \\\  -  /// |   |
 *                     | \_|  ''\---/''  |   |
 *                     \  .-\__  `-`  ___/-. /
 *                   ___`. .'  /--.--\  `. . __
 *                ."" '<  `.___\_<|>_/___.'  >'"".
 *               | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *               \  \ `-.   \_ __\ /__ _/   .-` /  /
 *          ======`-.____`-.___\_____/___.-`____.-'======
 *                             `=---='
 *          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *                     佛祖保佑        永无BUG
 *            佛曰:
 *                   写字楼里写字间，写字间里程序员；
 *                   程序人员写程序，又拿程序换酒钱。
 *                   酒醒只在网上坐，酒醉还来网下眠；
 *                   酒醉酒醒日复日，网上网下年复年。
 *                   但愿老死电脑间，不愿鞠躬老板前；
 *                   奔驰宝马贵者趣，公交自行程序员。
 *                   别人笑我忒疯癫，我笑自己命太贱；
 *                   不见满街漂亮妹，哪个归得程序员？
 */
@WebServlet(value = "/cartservlet")
public class CartServlet extends BaseServlet {
    public String addCart(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        //1接收数据
        String goodsId = request.getParameter("goodsId");
        String number = request.getParameter("number");
        int num=1;
        //2判断
        if(StringUtils.empty(goodsId)){
            request.setAttribute("msg","添加购物车失败" );
            return "/message.jsp";
        }
        if(!StringUtils.empty(number)){
            num=Integer.parseInt(number);
            if(num<1||num>5){
                num=1;
            }
        }
        //3创建业务对象
        //查询商品
        try {
            GoodsService goodsService=new GoodsServiceImpl();
            Goods goods=goodsService.findById(Integer.parseInt(goodsId));
            if(goods!=null) {
                CartService cartService = new CartServiceImpl();
                // 查询购物车中是否已经有这个商品了
                CartItem cartItem=cartService.findCart(user.getId(),goods.getId());
                if(cartItem==null) {//添加
                    cartItem = new CartItem(user.getId(), goods.getId(), num, goods.getPrice().multiply(new BigDecimal(num)));
                    cartService.add(cartItem);
                }else{//更新
                    cartItem.setNum(cartItem.getNum()+num);
                    cartItem.setMoney(goods.getPrice().multiply(new BigDecimal(cartItem.getNum())));
                    cartService.modify(cartItem);
                }
                return "/cartSuccess.jsp";
            }else{
                request.setAttribute("msg","商品不存在" );
                return "/message.jsp";
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","添加购物项失败" );
            return "/message.jsp";
        }
    }

    public String getCart(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        //创建业务对象
        CartService cartService=new CartServiceImpl();
        List<CartItem> cartItems= cartService.findCart(user.getId());
        request.setAttribute("cartItems", cartItems);
        return "/cart.jsp";
    }

    //执行ajax请求的方法
    public String addCartAjax(HttpServletRequest request,HttpServletResponse response) throws Exception{

        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }

        String goodsId = request.getParameter("goodsId");
        String number = request.getParameter("number");

        if(StringUtils.empty(goodsId)){
            return  null;
        }
        if(StringUtils.empty(number)){
            return null;
        }
        //更新操作
        CartService cartService=new CartServiceImpl();
        CartItem cartItem=cartService.findCart(user.getId(), Integer.parseInt(goodsId));
        if(cartItem!=null){
            //更新  1 和 -1
            int num=Integer.parseInt(number);
            if(num!=0){//更新
                cartItem.setNum(cartItem.getNum()+num);
                //如果更新之后 数量为<1
                if(cartItem.getNum()<1){
                     //删除
                    cartService.delete(user.getId(),Integer.parseInt(goodsId));
                }else{
                    //更新
                    GoodsService goodsService=new GoodsServiceImpl();
                    Goods goods = goodsService.findById(Integer.parseInt(goodsId));
                    cartItem.setMoney(goods.getPrice().multiply(new BigDecimal(cartItem.getNum())));
                    cartService.modify(cartItem);
                }

            }else{ //num==0
                //删除
                cartService.delete(user.getId(),Integer.parseInt(goodsId));
            }
        }
        return null;
    }
    //清空购物车
    public String clearCartAjax(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        CartService cartService=new CartServiceImpl();
        cartService.delete(user.getId());
        return null;
    }
}
